﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.Support;
using Microsoft.SharePoint;

namespace MS.InformationManagement.Core.Actions
{
    public class VoBoAssignDocumentsPermissionCommand : IBaseCommand
    {

        #region Fields

        string _targetUser;
        SPListItem _currentItem;

        #endregion

        #region Constructors

        public VoBoAssignDocumentsPermissionCommand(string targetUser, SPListItem targeItem)
        {
            _targetUser = targetUser;
            _currentItem = targeItem;
        }

        #endregion

        public void Execute()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        SPRoleDefinition oRole = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                        SPRoleAssignment roleAssignment = new SPRoleAssignment(web.SiteUsers[_targetUser]);
                        roleAssignment.RoleDefinitionBindings.Add(oRole);
                        _currentItem.BreakRoleInheritance(true);
                        _currentItem.RoleAssignments.Add(roleAssignment);
                        _currentItem.Update();
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });                
        }

        public void Undo()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        _currentItem.RoleAssignments.Remove(web.SiteUsers[_targetUser]);
                        _currentItem.Update();
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });                
        }
    }
}
